<?php
class wxpayModel extends appModel{
	/**
	 *获得一条微信record记录
	 */
	public function get_record($id)
	{
		if(!$id)
		{
			return false;
		}
		$sql = "SELECT *,nickname as name FROM ".$this->table('wxusers')." WHERE wxid =".$id;
		$result=$this->getRow($sql);

		if($result)
		{

			return $result;
		}
		else
		{
			return false;
		}
	}
	
	
	public function get_out_trade_no($mch_id,$app='',$time=0){
		$out_trade_no = $mch_id.date("YmdHis").$app;
		$sql = "SELECT COUNT(id) FROM ".$this->table("wx_pay")." WHERE out_trade_no = '".$out_trade_no."'";
		$count = $this->getOne($sql);
		if($count){//有值
			if($time<8){
				$time++;
			}
			$append = hy_rand($time);
			$this->get_out_trade_no($mch_id,$append,$time);
		}else{//无值
			return $out_trade_no;
		}
			
	}
	
	
	public function get_wx_pay_by_trade($out_trade_no){
		$sql = "SELECT pay_status,transaction_id FROM ".$this->table('wx_pay')." WHERE out_trade_no='".$out_trade_no."'  LIMIT 1 ";
		$res = $this->getRow($sql);
		if($res['payStatus']=="SUCCESS"&&$res['transaction_id']!=""){
			return false;
		}
		$sql = "SELECT id FROM ".$this->table('wx_pay')." WHERE out_trade_no='".$out_trade_no."' LIMIT 1 ";
		$payId = $this->getOne($sql);
		return $payId;
	}
	
	public function get_id_by_trade($out_trade_no){
		$sql = "SELECT id FROM ".$this->table('wx_pay')." WHERE out_trade_no='".$out_trade_no."' LIMIT 1 ";
		$payId = $this->getOne($sql);
		return $payId;
	}
	
	public function is_pay($out_trade_no){
	$sql = "SELECT pay_status FROM ".$this->table('wx_pay')." WHERE out_trade_no='".$out_trade_no."' LIMIT 1 ";
		$payStatus = $this->getOne($sql);
		if($payStatus=="SUCCESS"){
			return true;
		}
		return false;
	}
	
	public function get_wx_pay_by_id($id,$wxid){
		$time = date("YmdHis");
		$sql ="SELECT prepay_id,out_trade_no,pay_status  FROM ".$this->table("wx_pay")." WHERE id=$id AND wxid = $wxid AND time_expire>=$time  LIMIT 1";
		$res = $this ->getRow($sql);
		if($res){
			return $res;
		}
		return false;
	}
	
	public function is_saved_user($wxid){
		$sql = "SELECT COUNT(*) FROM ".$this->table('wx_pay_user')." WHERE wxid = $wxid";
		$count = $this->getOne($sql);
		if($count){
			return false;
		}else{
			return true;
		}
	}
	
	public function push_code_sub_money($codes){
		$sql = "SELECT COUNT(*) FROM ".$this->table('wx_pay_code')." WHERE codes = '".$codes."'";
		$count = $this->getOne($sql);
		if($count){
			$sql="SELECT * FROM ".$this->table('wx_pay_code')." WHERE codes='".$codes."' LIMIT 1";
			return $this->getRow($sql);
		}else{
			return false;
		}
	}
}